package com.jch.learn.demo;

import com.jch.learn.demo.code.BasicQueue;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Random;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {

    public static BasicQueue bq;

    static {
        try {
            bq = new BasicQueue("queue/", "test");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static AtomicInteger atomicInteger = new AtomicInteger(0);

    public static void main(String[] args) {
        LinkedBlockingDeque<Integer> deque = new LinkedBlockingDeque<>(10);
        try {
            deque.add(1);
            deque.put(1);
            deque.peek();
            deque.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < 10; i++) {
            new Thread(new ProducerThread(), "Producer" + (i + 1)).start();
        }

        new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    while (true) {
                        byte[] msgBytes = bq.dequeue();
                        if (msgBytes == null) {
                            Thread.sleep(100);
                            continue;
                        }
                        System.out.println("Thread Name:" + Thread.currentThread().getName());
                        System.out.println("Consumer:" + new String(msgBytes,StandardCharsets.UTF_8));
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "Consumer").start();

    }

    private static class ProducerThread implements Runnable {

        @Override
        public void run() {
            try {
                Random r = new Random();

                while (true) {
                    String msg = new String("test" + (atomicInteger.addAndGet(1)));
                    bq.enqueue(msg.getBytes(StandardCharsets.UTF_8));
                    System.out.println("Thread Name:" + Thread.currentThread().getName());
                    System.out.println("Producer:" + msg);
                    Thread.sleep(r.nextInt(10000));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
